const {
    MIME_TYPE_EPUB,
    OLD_UPLOAD_URL,
    MIME_TYPE_RESUME,
    UPLOAD_URL,
    UPLOAD_PATH
} = require('../utils/constant')
const fs = require('fs')
const path = require('path')
const Epub = require('../utils/epub')
const xml2js = require('xml2js').parseString

class Enroll {
    constructor(file, data) {
        if (file) {
            this.createBookFromFile(file)
        } else {
            this.createBookFromData(data)
        }
    }
    createBookFromFile(file) {
        // console.log('createBookFromFile', file)
        const {
            destination,
            filename,
            mimetype = MIME_TYPE_RESUME,
            path,
            originalname
        } = file
        // 电子书的文件后缀名
        const suffix = mimetype === MIME_TYPE_RESUME ? '.jpg' : ''
        // 电子书的原有路径
        const oldBookPath = path
        // 电子书的新路径
        const bookPath = `${destination}/${filename}${suffix}`
        // 电子书的下载URL
        const url = `${UPLOAD_URL}/enroll/${filename}${suffix}`
        

        if (fs.existsSync(oldBookPath) && !fs.existsSync(bookPath)) {
            fs.renameSync(oldBookPath, bookPath)
        }
        this.fileName = filename // 文件名
        this.path = `/enroll/${filename}${suffix}` // jpg文件相对路径
        this.filePath = this.path
        this.url = url // jpg文件下载链接
        this.title = '' // 书名
        this.author = '' // 作者
        this.originalName1=originalname
        this.originalName = `${UPLOAD_URL}/enroll/${this.originalName1}.${suffix}` // 电子书文件的原名
    }

    createBookFromData(data) {
        this.username = data.title
        this.password = data.attribute
        this.role = data.abstract
        this.nickname = data.nickname

    }
    parse(usernameinfo) {
        return new Promise((resolve, reject) => {
            const resumePath = `${UPLOAD_PATH}${this.filePath}`
            if (!fs.existsSync(resumePath)) {
                reject(new Error('图片不存在'))
            }
            const oldFile = `${UPLOAD_PATH}/enroll/${this.fileName}`;
            const suffix = MIME_TYPE_RESUME.split('/')[1]
            const newFile = `${UPLOAD_PATH}/enroll/${this.fileName}.${suffix}`
            const URLdizhi= `${UPLOAD_URL}/enroll/${this.fileName}.${suffix}`
            const Img= {'originalName':this.originalName1,'url':URLdizhi}
            fs.rename(oldFile, newFile, (err) => {
                  
                
            })
            resolve(Img)

        })
    }

    toDb() {
        return {
            username: this.username,
            password : this.password,
            role :this.role,
            nickname :this.nickname,
            avatar:this.originalName

        }
    }

}
module.exports = Enroll
